<template>
  <!-- 设备责任范围表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="1000px"
      draggable
      @close="closeDialog"
    >
      <el-form
        v-show="!props.isReadonly"
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100"
      >
        <div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="责任范围" prop="liabilityExtent">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.liabilityExtent"
                  placeholder="请输入责任范围"
                  clearable
                  style="width: 90%"
                />
                <span v-else>{{ formData.liabilityExtent }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="责任设备" prop="equipIds">
                <el-select
                  style="width: 90%"
                  v-if="!props.isReadonly"
                  v-model="formData.equipIds"
                  placeholder="请选择设备"
                  clearable
                  filterable
                  multiple
                >
                  <el-option
                    v-for="item in equipList"
                    :key="item.id"
                    :label="item.equipCode"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="责任人" prop="personIds">
                <el-select
                  ref="selectRef"
                  v-model="formData.personIds"
                  multiple
                  placeholder="请选择人员"
                  :collapse-tags="true"
                  :collapse-tags-tooltip="true"
                  :max-collapse-tags="2"
                  style="width: 90%"
                  @visible-change="openSelectOriganization"
                  @remove-tag="removeSelection"
                >
                  <el-option
                    v-for="item in personOptions"
                    :key="item.userId"
                    :label="`${item.userName}${
                      item.empNo ? '(' + item.empNo + ')' : ''
                    }`"
                    :value="item.userId"
                  />
                </el-select>
<!--                <el-select-->
<!--                  style="width: 90%"-->
<!--                  v-if="!props.isReadonly"-->
<!--                  v-model="formData.personIds"-->
<!--                  placeholder="请选择责任人"-->
<!--                  clearable-->
<!--                  multiple-->
<!--                  filterable-->
<!--                >-->
<!--                  <el-option-->
<!--                    v-for="item in userList"-->
<!--                    :label="item.firstName"-->
<!--                    :value="item.id"-->
<!--                    :key="item.id"-->
<!--                  />-->
<!--                </el-select>-->
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <el-descriptions
        v-show="props.isReadonly"
        class="margin-top"
        :column="1"
        size="large"
        border
      >
        <el-descriptions-item label="责任范围">
          <div style="width: 100%; word-break: break-all">
            {{ formData.liabilityExtent }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="责任设备">
          <div style="width: 100%; word-break: break-all">
          {{ formData.equipCodes }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="责任人">
          <div style="width: 100%; word-break: break-all">
          {{ formData.personNames }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 审核人 弹窗组件 -->
  <SelectPersonDialog
    v-model:visible="personSelect.visible"
    :data="personSelect.data"
    @echo-info="getPersonSelect"
    :isMultiple="true"
    key="1"
  />
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { getMdmProcessEquipApi1 } from "@/utils/commonData"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMEFALIABILITYEXTENTADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  type: {
    type: Number,
    required: true,
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
    if (newVal) {
      getEquipList({});
      getUserList();
    }
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  liabilityExtent: "",
  type: null,
  enabled: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  lastUpdateTime: "",
  equipIds: [],
  personIds: [],
  equipCodes: "",
  personNames: "",
  details: [],
  persons: [],
});

/** rules规则 */
const rules = reactive({
  liabilityExtent: [
    { required: true, message: "请输入责任范围", trigger: "blur" },
  ],
  equipIds: [{ required: true, message: "请选择设备", trigger: "blur" }],
  personIds: [{ required: true, message: "请选择责任人", trigger: "blur" }],
});

const isValidated = ref(false);

const details = {
  id: "",
  liabilityExtentId: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  lastUpdateTime: "",
};
/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
        getPersons();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.equipIds = [];
  formData.equipCodes = "";
  formData.personIds = [];
  formData.persons = [];
  formData.personNames = "";
  formData.id = "";
  formData.liabilityExtent = "";
  formData.type = null;
  formData.enabled = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.lastUpdateTime = "";
  personOptions.value = [];
}

const loading = ref(false);

/** 设备责任范围保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      formData.type = props.type;
      console.log("formData", toRaw(formData));
      formData.details = formData.equipIds.map((item: any) => {
        const find = equipList.value.find((equip) => equip.id === item);
        return {
          equipCode: find?.equipCode,
          equipName: find?.equipName,
          equipId: item,
        };
      });
      formData.persons = formData.personIds.map((item: any) => {
        const find = userList.value.find((user) => user.id === item);
        return {
          userName: find?.firstName,
          userId: item,
        };
      });
      await request({
        url: "/eam/efaliabilityextent/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/eam/efaliabilityextent/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
  formData.equipIds = formData.details.map((item: any) => item.equipId);
  formData.equipCodes = formData.details
    .map((item: any) => item.equipCode)
    .join(",");
}
async function getPersons() {
  let sondetails = await request({
    url: "/eam/efaliabilityextent/getPersons",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.persons = sondetails.data;
  personOptions.value = formData.persons
  formData.personIds = formData.persons.map((item: any) => item.userId);
  formData.personNames = formData.persons
    .map((item: any) => item.userName)
    .join(",");
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(params: Object) {
  equipList.value = (await getMdmProcessEquipApi1(params)) || [];
}
// 负责人
const userList = ref<any>([]);
const getUserList = async () => {
  await request({
    url: "/system/sysUser/getList",
    method: "post",
    data: { enabled: 1 },
  }).then((res) => {
    userList.value = res.data;
  });
};


const personOptions: any = ref([]); // 选择器 model ids
const selectRef = ref(); // 选择器 ref

// 定义 人员选择器弹窗参数
const personSelect = reactive({
  visible: false,
  data: [],
});

// 打开 人员选择器弹窗
function openSelectOriganization(event: boolean) {
  if (event) {
    selectRef.value.blur(); // 隐藏下拉框
    personSelect.visible = true;
    const newOptions: any = [];
    personOptions.value.map((e: any) =>
      newOptions.push({
        id: e?.userId,
        firstName: e?.userName,
        empNo: e?.empNo,
      })
    );
    personSelect.data = newOptions;
  }
}

/** 打开最终审核人员选择器方法   start **/
interface SelectOption {
  id?: string;
  userId?: string;
}
// 移除 人员tag标签
function removeSelection(id: SelectOption) {
  // ElMessageBox.confirm("确认删除当前数据项?", "提示", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning",
  // }).then(async () => {
  personOptions.value.forEach((row: SelectOption, index: number) => {
    if (row.userId === id) personOptions.value.splice(index, 1);
  });
  // });
}
interface LeaderTS {
  id?: string;
  roleId?: string;
  roleName?: string;
  roleType?: number;
  userName?: string;
  userId?: string;
  firstName?: string;
  empNo?: string;
}
// 接收 人员选择器回调参数
function getPersonSelect(options: any) {
  const newOptions: any = [];
  options.map((e: LeaderTS) =>
    newOptions.push({
      userId: e?.id,
      userName: e?.firstName,
      empNo: e?.empNo,
      userType: 5,
    })
  );
  personOptions.value = newOptions;
  const ids: any = [];
  options?.map((item: SelectOption) => ids.push(item.id));
  formData.personIds = ids || [];
}

</script>

<style lang="scss" scoped></style>
